﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Web.UI;
using UDS.Components;

namespace UDS.SubModule.Login
{
    /// <summary>
    /// index 的摘要说明。
    /// </summary>
    public partial class IndexPage : Page
    {
        public string RandData;
        private const string LastUserNameCookie = "user_pre";

        private static byte[] hexstr2array(string HexStr)
        {
            const string HEX = "0123456789ABCDEF";
            string str = HexStr.ToUpper();
            int len = str.Length;
            var RetByte = new byte[len / 2];
            for (int i = 0; i < len / 2; i++)
            {
                int NumHigh = HEX.IndexOf(str[i * 2]);
                int NumLow = HEX.IndexOf(str[i * 2 + 1]);
                RetByte[i] = Convert.ToByte(NumHigh * 16 + NumLow);
            }
            return RetByte;
        }

        protected override void OnInit(EventArgs e)
        {
            btnSubmit.Click += btnSubmit_Click;
            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            //执行是否需要USB_key的JavaScript
            btnSubmit.Attributes["onclick"] = "return needUsbKey();";

            if (!Page.IsPostBack)
            {
                var randomGenerator = new Random(DateTime.Now.Millisecond);
                for (int i = 0; i < 19; i++)
                {
                    RandData += Convert.ToChar(randomGenerator.Next(97, 122));
                }

                var cookie = Request.Cookies[LastUserNameCookie];
                txtUsername.Text = cookie != null ? cookie.Value : "";
            }

            base.OnLoad(e);
        }

        public int LoginIn(string ServerString, string ClientString)
        {
            //string username = Request.Form["SN_SERAL"];
            //string clientdigest = Request.Form["Digest"];

            //these for MD5_HMAC
            string ipad = "";
            string opad = "";

            for (int i = 0; i < 64; i++)
            {
                ipad += "6";
                opad += "\\";
            }

            const string Password = "0";
            int KLen = Password.Length;
            string iResult = "";
            for (int i = 0; i < 64; i++)
            {
                if (i < KLen)
                {
                    iResult += Convert.ToChar(ipad[i] ^ Password[i]);
                }
                else
                {
                    iResult += Convert.ToChar(ipad[i]);
                }
            }

            iResult += ServerString;
            iResult = Utility.ComputeHash(iResult);

            byte[] Test = hexstr2array(iResult);
            iResult = "";
            char[] b = Encoding.GetEncoding(1252).GetChars(Test);

            for (int i = 0; i < b.Length; i++)
            {
                iResult += b[i];
            }

            string oResult = "";
            {
                for (int i = 0; i < 64; i++)
                {
                    if (i < KLen)
                        oResult += Convert.ToChar(opad[i] ^ Password[i]);
                    else
                        oResult += Convert.ToChar(opad[i]);
                }
            }

            oResult += iResult;

            string Result = Utility.ComputeHash(oResult).ToUpper();
            if (Equals(Result, ClientString))
                return 1;
            return 0;
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            bool needUSBKey;
            var staff = new Components.Staff();
            var userName = txtUsername.Text.Trim();
            var userId = staff.Login(userName, txtPassword.Text, out needUSBKey);
            if (userId <= 0)
            {
                // Invalid username or password.
                lblErrorMessage.Visible = true;
                return;
            }

            if (needUSBKey)
            {
                // Check the USB settings.
                string ClientDigest = Request.Form["Digest"] == null ? "" : Request.Form["Digest"];
                string ErrMsg = Request.Form["ErrMsg"] == null ? "" : Request.Form["ErrMsg"];

                if (LoginIn(RandData, ClientDigest) == 0)
                {
                    if (ErrMsg != "")
                        lblErrorMessage.Text = ErrMsg;
                    else
                        lblErrorMessage.Text = "EPass校验未通过！";
                    lblErrorMessage.Visible = true;
                    return;
                }
            }

            // 更新在线人数表
            SMS.UpdateOnlineInfo(userName, Request.UserHostAddress, SiteContext.Current.SessionID.ToString());

            // 更新结束
            SiteContext.Current.ActiveNodeID = 0;
#if false
                Response.Cookies["UserID"].Value = UserID;
                Response.Cookies["Username"].Value = txtUsername.Text;
                Response.Cookies["UserID"].Expires = new DateTime(2010, 1, 1);
                Response.Cookies["Username"].Expires = new DateTime(2010, 1, 1);
                if (FormsAuthentication.GetRedirectUrl(UserID, false).ToLower().EndsWith("default.aspx"))
                {
                    FormsAuthentication.SetAuthCookie(UserID, false);
                    //弹出窗口
                    //Server.Transfer("VerifySignIn.aspx");
                    //非弹出窗口
                    Response.Redirect("~/SubModule/Index.aspx");
                }
                else
                {
                    FormsAuthentication.RedirectFromLoginPage(UserID, false);
                }
#endif

            Response.Cookies[LastUserNameCookie].Value = txtUsername.Text;
            Response.Cookies[LastUserNameCookie].Expires = DateTime.Now.AddYears(1);

            SiteContext.Current.LoginAndRedirect(userId, userName);

        }
    }
}